package com.tarena.lbs.content.feign;

import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.common.encoder.JwtEncoder;
import com.tarena.lbs.common.principle.UserPrinciple;
import com.tarena.lbs.common.utils.AuthenticationContextUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RequiredArgsConstructor
public class FeignAuthInterceptor implements RequestInterceptor {
    private final JwtEncoder<UserPrinciple> jwtEncoder;
    @Override
    public void apply(RequestTemplate template) {
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();
        log.info("Feign请求拦截器获取用户信息:{}",userPrinciple);
        if (userPrinciple != null) {
            try {
                String token = jwtEncoder.generateToken(userPrinciple);
                template.header("Authorization",token);
                log.info(token);
            }catch (BusinessException e){
                log.error("Feign请求拦截器生成token失败,{}",e.getMessage());
            }
        }
    }
}
